package com.econ.powercloud.ems.util;

import lombok.NonNull;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author zhki
 * @date 2022/11/1 16:11
 * @description 获取spring容器相关信息
 */
@Component
public class SpringContextUtil implements ApplicationContextAware {
    private static ApplicationContext ctx = null;

    public static void setCtx(ApplicationContext ctx) {
        SpringContextUtil.ctx = ctx;
    }

    /**
     * 获取上下文环境 获取spring的ApplicationContext
     *
     * @return ApplicationContext
     */
    public static ApplicationContext getApplicationContext() {
        return ctx;
    }

    /**
     * 通过名称获取spring管理的bean
     *
     * @param name String
     * @return Object
     */
    public static Object getBean(String name) {
        if (ctx == null) {
            ctx = getApplicationContext();
        }
        return ctx.getBean(name);
    }

    /**
     * 通过类型获取spring管理的bean（此方法在此类型只有一个实例时使用）
     *
     * @param clazz Class<T>
     * @return T
     */
    public static <T> T getBean(Class<T> clazz) {
        if (ctx == null) {
            ctx = getApplicationContext();
        }
        return ctx.getBean(clazz);
    }

    /**
     * 通过类型获取spring管理的bean（此方法在此类型有多个实例时使用）
     *
     * @param clazz Class<T>
     * @return T
     */
    public static <T> Map<String, T> getBeansOfType(Class<T> clazz) {
        if (ctx == null) {
            ctx = getApplicationContext();
        }
        return ctx.getBeansOfType(clazz);
    }

    @Override
    public void setApplicationContext(@NonNull ApplicationContext applicationContext) throws BeansException {
        SpringContextUtil.setCtx(applicationContext);
    }
}
